<template>
    <div>
        <el-drawer :model-value="visible" title="录入结款记录" size="500px" @close="closeHandle" @closed="closed">
            <div class="demo-drawer__content">
                <el-form :model="form" ref="formRef" :rules="formRules" label-position="right">
                    <el-form-item label="结款账户" required prop="jiekuanzhanghu_id" :label-width="formLabelWidth">
                        <el-select v-model="form.jiekuanzhanghu_id" filterable default-first-option :reserve-keyword="false"
                            placeholder="请选择结款账户">
                            <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <!-- 选择供应商 -->
                    <el-form-item label="供应商" required prop="gongyingshang_id" :label-width="formLabelWidth">
                        <el-select v-model="form.gongyingshang_id" filterable default-first-option :reserve-keyword="false"
                            placeholder="请选供应商">
                            <el-option v-for="item in company" :key="item.value" :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="款项金额" prop="price" required :label-width="formLabelWidth">
                        <el-input v-model="form.price" placeholder="请输入款项金额" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="最晚结款日期" prop="date" required :label-width="formLabelWidth">
                        <el-date-picker v-model="form.date" type="date" placeholder="请选择日期" :size="size" />
                    </el-form-item>
                    <el-form-item label-position='left' label="备注内容" prop="content" :label-width="formLabelWidth">
                        <!-- <el-input placeholder="请输入资料内容" v-model="form.content" show-word-limit rows="4" type="textarea"
                       autocomplete="off"/> -->
                        <div style="border: 1px solid #ccc">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                                :defaultConfig="toolbarConfig" :mode="mode" />
                            <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content"
                                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <el-space>
                    <el-button type="info" plain :loading="loading" @click="cancelHandle">取消</el-button>
                    <el-button type="primary" :loading="loading" @click="confirmHandle">提交保存</el-button>
                </el-space>
            </template>
        </el-drawer>
    </div>
</template>
  
<script setup>
import getConf from '@/views/news-upload/conf.js'
import { ref, reactive, computed, watch, onBeforeUnmount, shallowRef, onActivated } from "vue";
import { getBusinessId, addBusiness } from "@/api/business";
import { addProject, editProject } from "@/api/project";
import { platformInformation, platformType, addInformation } from '@/api/information'
import { gongyingshangvalue, commissionSubmit } from "@/api/commission"
import { settlementList } from "@/api/business";

// 获取供应商列表






import { STATUS_ENUM } from "@/views/project-list/status";
import { toast } from "@/hook/toast";
import { delay } from "@/utils";
import store from '@/store'

import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

const editorRef = shallowRef()
const valueHtml = ref('')

const FILE_LIST = ref([])

const toolbarConfig = {}

const getFilename = (src) => {
    const reg = /^[\s\S]+\/static\/([\s\S]+)$/
    const srcExec = reg.exec(src)
    if (srcExec) {
        return srcExec[1]
    }
}

const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: getConf(
        (src) => {
            const name = getFilename(src)
            if (name) {
                FILE_LIST.push(name)
            }
        },
    ),
}



const mode = 'default'
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 上传图片的地址
// editorConfig.MENU_CONF['uploadImages'] = {
//      server: '/common/upload',
// }






const form = reactive({
    // 客户资料
    xiangmu_id: '',
    kuanxiang_jieduan: "",
    pric: "",
    content: '',
    date: '',
    xiangmupricelog_id: '',
    // 供应商id
    gongyingshang_id: '',
    // 结款账户id
    jiekuanzhanghu_id: '',
    // 项目款结算id
    jiekuanlog_id: ''






});
const formRules = computed(() => ({

    name: [
        {
            required: true,
            message: '请输入项目名称',
            trigger: 'change',
        }
    ],
    gongqi: [
        {
            required: true,
            message: '请输入工期',
            trigger: 'change',
        }
    ],
}))
const formRef = ref(null)
const loading = ref(false);
const radio = ref('客户资料')
// 定义上传图片数组
const fileList = ref([])
// 定义上传 文件
const fileList2 = ref([])


// token 

const headerObj = ref({})
const { hasLogin, token } = store.getters
headerObj.value.token = token;


function getImageUrl() {
    // Editor.getMenuConfig('uploadImage') // 获取 uploadImage 的当前配置
}

// 上传图片 后
function handleRemove(uploadFile, uploadFiles) {

}
// 查看图片
function handlePreview(file) {
}
const images = ref([])
// 上传图片后展示
function successUpdata(e) {
    images.value.push(e.data.fullurl)

}
const files = ref([])
// 上传文件
function successFile(e) {
    files.value.push(e.data.fullurl)
}

const size = ref("default");
const formLabelWidth = "80px";
const statusEnum = computed(() => STATUS_ENUM)
const props = defineProps({
    modelValue: {
        type: Boolean,
        required: true,
    }
})
const emits = defineEmits(['update:modelValue', 'addSuccess'])

const cancelHandle = () => {
    visible.value = false
}
function closed() {
    resetForm()
}
const imageUrl = ref('')

// 触发单选
function changeRadio(e) {
    // 选择单选完之后
    radio.value = e
    getPlatform()
}
const visible = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emits('update:modelValue', value)
    }
})

// 结款列表
const userList = ref([])
async function initUserList() {
    const resp = await settlementList()
    console.log(resp, 'huoqu')
    const { code, data, msg } = resp
    if (code !== 1) return
    if (!!data.data && data.data.length) {
        userList.value = data.data.map(item => {
            const { id, name } = item
            return { value: id, label: name }
        })
    }





}

// 获取的款项账户
// const settlementDataList = ref([])
// async function gteSettlementList() {
//     const resp = await settlementList()
//     const { code, data, msg } = resp
//     if (code !== 1) return



//     if (!!data.data && data.data.length) {
//         settlementDataList.value = data.data.map(item => {
//             const { id, name } = item
//             return { value: id, label: name }
//         })
//     }

// }


// 获取供应商列表
const company = ref([])
async function companyList() {
    const resp = await gongyingshangvalue()
    const { code, data, msg } = resp
    if (code !== 1) return
    if (!!data && data.length) {
        company.value = data.map(item => {
            const { id, name } = item
            return { value: id, label: name }
        })
    }
    console.log('查看公寓', company)
}
// 获取资料
const platformTypeData = ref([])
async function getPlatform() {
    platformTypeData.value = [];
    const ziliao_type = radio.value
    const resp = await platformType({ ziliao_type })
    const { code, data, msg } = resp
    if (code !== 1) return
    if (!!data && data.length) {
        platformTypeData.value = data.map(item => {
            const { id, name } = item
            return { value: id, label: name }
        })
    }
}
const ziliao_ids = ref('')
// 选择资料的时候
function changeClick(e) {
    ziliao_ids.value = e
}
// 清空数据
function resetForm() {
    form.xiangmu_id = ''
    form.kuanxiang_jieduan = ''
    form.kuanxiang_price = ''
    form.content = ''
    form.end_date = ''
    form.xiangmupricelog_id = ''
    formRef.value.resetFields()
}

watch(() => props.modelValue, value => {
    if (!value) {
        return
    }
    initUserList()
    companyList()
})

const closeHandle = () => {
    visible.value = false
};
function editHandle(row) {
    const {
        content,
        id,
        end_date,
        kuanxiang_price,
        xiangmu_id,
        jieduan_id,
    } = row

    form.kuanxiang_jieduan = jieduan_id
    form.xiangmu_id = xiangmu_id
    form.end_date = end_date
    form.kuanxiang_price = kuanxiang_price
    if (id) {
        form.jiekuanzhanghu_id = id
    }
    if (content) {
        form.content = decodeURIComponent(content) || '';
    }
    if (!isNaN(row)) {
        form.xiangmu_id = row
    }
    visible.value = true
    form.isEdit = true
}

defineExpose({
    editHandle,
})


onActivated(() => {
    // console.log(FILE_LIST)
    // if (!isEditor.value) {
    // 	return
    // }
    // initNews(isEditor.value)
    getImageUrl()
})


function reqMethod(data) {
    if (form.isEdit) return editProject(data)
    return addProject(data)
}

function confirmHandle() {
    formRef.value.validate(async flag => {
        if (!flag) return
        loading.value = true
        const { xiangmu_id, price, date, content, jiekuanlog_id, gongyingshang_id, jiekuanzhanghu_id } = form
        const htmlVl = encodeURIComponent(content)
        const payload = {
            xiangmu_id, price, date, content: htmlVl, jiekuanlog_id, gongyingshang_id, jiekuanzhanghu_id
        }
        console.log(payload, '数据2')
        const resp = await commissionSubmit(payload)
        form.isEdit = false
        const { code, msg } = resp
        await delay(200)
        toast({ title: msg })
        loading.value = false
        if (code !== 1) return
        triggerUpdate()
    })
}

function triggerUpdate() {
    emits('addSuccess')
    resetForm()
    visible.value = false
}
</script>
  